<template>
  <div class="search">
    <form action="/">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch(searchText)"
        @cancel="$router.back()"
        @focus="isResultShow = false"
      />
      <!--相当于把搜索结果关掉了-->
    </form>

<!-- search是子传父传过来的-->
    <searchResult v-if="isResultShow" :searchText="searchText" />
    <searchSuggestion
      v-else-if="searchText"
      :searchText="searchText"
      @search="onSearch"
    />
    <searchHistory :searchHistories="searchHistories" v-else @search="onSearch" @updateHistories="searchHistories = $event"/>
  </div>
</template>

<script>
import searchHistory from "../components/search-history";
import searchSuggestion from "../components/search-suggestion";
import searchResult from "../components/search-result";
import {setItem,getItem} from '../utils/storage'
import {getSearchHistory} from '../api/search.js'
import {mapState} from 'vuex'
export default {
  name: "search",
  data() {
    return {
      // 搜索框输入内容
      searchText: "",
      isResultShow: false, //控制搜索结果的显示状态
      searchHistories: []   //搜索历史记录 没有读到数据就是一个空数组 与登录的合并先写一个空数组
    };
  },
  methods: {
    onSearch(searchText) {
      // 数据等于搜索框的内容
      this.searchText = searchText;
      
      const index = this.searchHistories.indexOf(searchText)
      if(index !==-1){
        // index不等于-1就是在数组中存在了 把重复项移除
        this.searchHistories.splice(index,1)
      }
      // 把最新的搜索历史记录搜索结果放到顶部
      this.searchHistories.unshift(searchText);

      // 如果用户已登录，则把搜索记录记录到线上
      // 调用存储的接口后端自动存储
      // 没登录把搜索记录存放到本地
      // setItem('searchHistories',this.searchHistories)
      // 展示搜索结果
      this.isResultShow = true;
    },
    async loadSearchHistories(){
      // 判断用户的登录状态
      let searchHistories = getItem('searchHistories') || []
      if(this.user){
      const {data} = await getSearchHistory()
      console.log(data.data.keywords)
      // 合并数组 es6语法 set直接去重  ...new Set[] 转成数组
      searchHistories = [...new Set([...searchHistories,...data.data.keywords])]
      }
      // console.log(localHistories)
      // 赋值
      this.searchHistories = searchHistories
    }
  },
  components: {
    searchSuggestion,
    searchHistory,
    searchResult
  },
  created(){
    // 登录的时候历史记录只返回四个，要与本地的合并
    this.loadSearchHistories()
  },
  watch: {
    // 通过监视统一处理历史记录的变化存储到本地
    searchHistories() {
      setItem("searchHistories", this.searchHistories);
    }
  }
};
</script>
<style scoped lang="less"></style>
